import { User } from '../models/UserModel';
import { BaseService } from './BaseService';
import UserRepository from '../schemas/UserSchema';
import * as bcrypt from 'bcrypt-nodejs';
import * as util from 'util';
import { logger } from '../common/logger';

/**
 * @class UserService
 */
export class UserService extends BaseService<User> {

    repository = UserRepository;

    usocket: object = {};

    /**
     * @description 广播消息
     * @param {string} eventName
     * @param {any} msg
     * @returns
     */
    async broadcastMsg(eventName: string, msg: any) {
        for (const socketId in this.usocket) {
            // 发消息
            logger.info(`Socket emit ${eventName} to ${socketId}: ${msg}`);
            this.usocket[socketId].emit(eventName, msg);
        }
    }

    /**
     * @description Fetches single user from the storage by email or name
     * @param {string} name
     * @param {string} email
     * @returns {Promise<User>}
     */
    async findByNameOrEmail(name: string, email: string): Promise<User> {
        const user: User = await this.repository.findOne({ $or: [{ email: email }, { name: name }] });
        return user;
    }

    /**
     * @description Compares encrypted and decrypted passwords
     * @param {string} candidatePassword
     * @param {string} storedPassword
     * @returns {boolean}
     */
    comparePassword(candidatePassword: string, storedPassword: string): boolean {
        const qCompare = (util as any).promisify(bcrypt.compare);
        return qCompare(candidatePassword, storedPassword);
    }
}

export { User };
